package com.haiyou.common.util;

import lombok.Getter;
import org.apache.commons.collections.MapUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 分页查询参数
 */
@Getter
public class PageQuery extends HashMap<String, Object> {
    //当前页
    private static final String PAGENUM = "pageNum";
    //每页的数量
    private static final String PAGESIZE = "pageSize";

    private int pageNum;
    private int pageSize;

    public PageQuery() {
    }

    public Integer getPageNum(HashMap<String, Object> params) {
        return MapUtils.getInteger(params, PAGENUM);
    }

    public Integer getPageSize(HashMap<String, Object> params) {
        return MapUtils.getInteger(params, PAGESIZE);
    }

    public static PageQuery build(Map<String, Object> pageParam) {
        return init(pageParam);
    }

    private static PageQuery init(Map<String, Object> pageParam) {
        PageQuery pageQuery = new PageQuery();
        pageQuery.putAll(pageParam);
        pageQuery.pageNum = MapUtils.getInteger(pageParam, PAGENUM, 1);
        pageQuery.pageSize = MapUtils.getInteger(pageParam, PAGESIZE, 10);
        pageQuery.put(PAGENUM, pageQuery.pageNum);
        pageQuery.put(PAGESIZE, pageQuery.pageSize);
        return pageQuery;
    }

    public void build(Example.Criteria criteria, String key, String value, Boolean isLike) {
        if (isLike) {
            criteria.andLike(key, "%" + value + "%");
        } else {
            criteria.andEqualTo(key, value);
        }
    }

    public void build(Example.Criteria criteria, String key, String value) {
        criteria.andEqualTo(key, value);
    }

    public void build(Example.Criteria criteria, String key, Integer value) {
        criteria.andEqualTo(key, value);
    }

    public void build(Example.Criteria criteria, String key, List value) {
        criteria.andIn(key, value);
    }

    public void build(Example.Criteria criteria, String key, Double value) {
        criteria.andEqualTo(key, value);
    }

    public void build(Example.Criteria criteria, String key, Float value) {
        criteria.andEqualTo(key, value);
    }

    public static PageQuery Instance(Integer pageSize, Integer pageNum) {
        HashMap<String, Object> params = RequestUtils.getParams();
        PageQuery pageQuery = new PageQuery();
        pageQuery.putIfAbsent("pageSize", pageSize);
        pageQuery.putIfAbsent("pageNum", pageNum);
        Optional.ofNullable(params).ifPresent(queryParams -> {
            pageQuery.putIfAbsent("params", params);
        });
        return pageQuery;
    }
}